<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>webSocket demo</title>
<script src="//cdn.bootcss.com/jquery/3.0.0-beta1/jquery.js"></script>
</head>
<body style="text-align: center;">
		<div>
			<textarea id="chatContent" style="width: 454px; height: 292px;" disabled="disabled"></textarea>
		</div>
		<div>
			<span>接收人ID：</span>
			<input id="sessionId" style="width: 369px;"/>
		</div>
		<div>
			<span>内&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;容：</span>
			<textarea id="messageText" style="width: 366px; height: 72px;"></textarea>
		</div>
		<div>
			<input id="sendBtn" type="button" value="发送" style="margin-left: 330px;"/>
			<input type="button" value="关闭连接" style="margin-left: 5px;" />
		</div>
</body>
<script type="text/javascript">

	// 我们连接到websocket 服务器端，使用构造函数 new WebSocket() 而且传之以端点URL：
	// ws://localhost:8081/Git/webSocketTest
	var webSocket = new WebSocket("ws://localhost:8081/Git/webSocketTest");
	
	// 我们创建一个连接到服务器的连接时将会调用此方法
	webSocket.onopen = function(event){
		console.log("连接已打开");
		console.log(event.data);
	}
	
	// 当客户端-服务器通信发生错误时将会调用此方法
	webSocket.onError = function(event){
		alert(event.data);
	}
	
	// 当从服务器接收到一个消息时将会调用此方法
	webSocket.onmessage = function (event){
		console.log(event.data);
		var message =event.data; 
		var json = JSON.parse(message);
		message = "发送人："+json.from+"\n内容："+json.content;
		
		var oldMessage = $("#chatContent").val();
		oldMessage+="\n"+message;
		
		$("#chatContent").val(oldMessage);
	}
	
	
	$("#sendBtn").click(function(){
		var to = $("#sessionId").val();
		var content = $("#messageText").val();
		
		var json = '{"to":"'+to+'","content":"'+content+'"}';
		webSocket.send(json);
	});
	
</script>
</html>